﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using D = System.Drawing;
using Microsoft.Practices.Prism.Regions;
using Infrastucture.Collections;
using TimeSplicerModule.DomainModels;
using TimeSplicerModule.ViewModels;
using TimeSplicerModule.Factories;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;
using TimeSplicerModule.Controllers;
using TimeSplicerModule.Security;
using TimeSplicerModule.Services;

namespace TimeSplicerModule.Views
{
    /// <summary>
    /// Interaction logic for TaskListView.xaml
    /// </summary>
    public partial class TaskListView : UserControl, INavigationAware
    {
        private TaskListViewModel Model;
        private ISession _session;
        private readonly IUnityContainer _container;
        private readonly ITaskService _taskService;
        private readonly ITaskController _taskController;
        private CancellationTokenSource _cancelToken;
        private TaskListViewModel _task = null;

        public TaskListView(IUnityContainer container, ITaskService taskService, ITaskController taskController)
        {
            InitializeComponent();

            _container = container;
            _taskService = taskService;
            _taskController = taskController;
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return false; //throw new NotImplementedException();
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            //throw new NotImplementedException();

            // wait cancel task -- oohh if this is it
            _cancelToken.Cancel(false);

            try
            {
                _cancelToken.Token.ThrowIfCancellationRequested();
            }
            catch (Exception ex)
            {

            }
        }

        public async void OnNavigatedTo(NavigationContext navigationContext)
        {
            this.progressBorder.Visibility = System.Windows.Visibility.Visible;
            this.progressRing.IsActive = true;

            _cancelToken = new CancellationTokenSource();
            _task = await Task.Run(() => Model = _taskService.GetTaskListViewModel(), _cancelToken.Token);
            
            Model = _taskService.GetTaskListViewModel();

            foreach (var t in Model.Tasks)
            {
                t.Status.BrushColor = t.Status.SetBrushColor();
            }

            this.progressBorder.Visibility = System.Windows.Visibility.Hidden;
            this.progressRing.IsActive = false;

            this.DataContext = Model;
        }

        private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListView list = sender as ListView;

            if (list.SelectedItem != null)
            {
                TaskModel task = list.SelectedItem as TaskModel;
                _taskController.NavigateToItemView(task.TaskGuid);
            }
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            taskSearch();
        }

        private void taskStatusesComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            taskSearch();
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            taskSearch();
        }

        private void taskSearch()
        {
            Model.SearchText = this.textSearchTextBox.Text;
            var user = this.usersComboBox.SelectedItem as UserModel;
            var status = this.taskStatusesComboBox.SelectedItem as StatusModel;

            if (String.IsNullOrEmpty(Model.SearchText))
            {
                if (status == null)
                    Model.FilteredTasks = Model.Tasks.Where(x => x.AssignedToGuid == user.UserGuid
                        && (x.Status.Status == Infrastucture.Status.In_Progress
                        || x.Status.Status == Infrastucture.Status.Suspended
                        || x.Status.Status == Infrastucture.Status.Not_Started)).OrderBy(O => O.Status.SortOrder).ToObservableCollection();
                else
                    Model.FilteredTasks = Model.Tasks.Where(x => x.AssignedToGuid == user.UserGuid
                        && x.StatusGuid == status.StatusGuid).OrderBy(O => O.Status.SortOrder).ToObservableCollection();
            }
            else
            {
                if (status == null)
                {
                    Model.FilteredTasks = Model.Tasks.Where(x => x.AssignedToGuid == user.UserGuid
                        && (x.Status.Status == Infrastucture.Status.In_Progress
                        || x.Status.Status == Infrastucture.Status.Suspended
                        || x.Status.Status == Infrastucture.Status.Not_Started)
                        && (x.Project.Name.ToLower().Contains(Model.SearchText.ToLower())
                        || x.Name.ToLower().Contains(Model.SearchText.ToLower()))).OrderBy(o => o.Status.SortOrder).ToObservableCollection();
                }
                else
                {
                    Model.FilteredTasks = Model.Tasks.Where(x => x.AssignedToGuid == user.UserGuid
                        && x.StatusGuid == status.StatusGuid
                        && (x.Project.Name.ToLower().Contains(Model.SearchText)
                        || x.Name.ToLower().Contains(Model.SearchText))).OrderBy(o => o.Status.SortOrder).ToObservableCollection();
                }
            }
        }
    }
}
